package easytalk.connectivity.googletalk;

import java.util.List;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;

import common.Discussion;
import common.DiscussionState;
import common.EasyChatEnvironment;
import common.EasyTalkException;
import common.Locutor;

import easytalk.dialogs.ChatDialogManager;

public class GoogleTalkChatManager implements ChatManagerListener {

	@Override
	public void chatCreated(Chat arg0, boolean arg1) {
		
		System.out.println("chat created : thrad id = " + arg0.getThreadID());
		Discussion discussion = EasyChatEnvironment.getInstance().findDiscussionById(arg0.getThreadID());
		if (discussion !=null) { //already exists discussion
			
			switch (discussion.getState()) {
			case CLOSED:
				break;
			case OFFLINE:
				break;
			case OPEN:
				break;
			case OPEN_DESCRETE:
				System.out.println("open discrete chat");
				break;
			case OPEN_WAITING:
				break;
			}
			ChatDialogManager.getInstance().updateDialogs();
			return;
		}
			
		Locutor locutor;
		try {
			locutor = EasyChatEnvironment.getInstance().getLocutorById(
					arg0.getParticipant(), new GoogleTalkIdComparator());
		} catch (EasyTalkException e) {
			e.printStackTrace();
			return;
		}
		
		List<Discussion> discussions = EasyChatEnvironment.getInstance().FindDiscussionsWith(locutor);
		if (! discussions.isEmpty()) {
			for (Discussion disc : discussions ) {
				
				switch (disc.getState()) {
				case CLOSED:
					break;
				case OFFLINE:
					break;
				case OPEN:
					break;
				case OPEN_DESCRETE:
					break;
				case OPEN_WAITING:
					break;
				}
			}
			ChatDialogManager.getInstance().updateDialogs();
			return;
		}
		
		discussion = EasyChatEnvironment.getInstance().createDiscussion(arg0.getThreadID());
		discussion.setData(arg0);
		
			discussion.addLocutor(locutor);
			discussion.setState(DiscussionState.OPEN);
			EasyChatEnvironment.getInstance().addDiscussion(discussion);
			ChatDialogManager.getInstance().updateDialogs();
			arg0.addMessageListener(new GoogleTalkMessageListener());
		
	}

}
